package xiao.ze.demo.controller;

import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.*;

import xiao.ze.demo.entity.User;
import xiao.ze.demo.service.UserService;

import javax.servlet.http.HttpServletRequest;

/**
 * SecurityController
 *
 * @author xiaoze
 * @date 2018/6/3
 *
 */
@Controller
@RequestMapping("/security")
public class SecurityController {

    @Autowired
    private UserService userService ;

    @RequestMapping("/index")
    public String root() {
        return "index";
    }

    @GetMapping("/toLogin")
    public String toLogin(Map<String, Object> map) {

        map.put("user", new User());

        return "login";
    }

    //注册页面
    @RequestMapping("/register")
    public String register(){
        return "register";
    }

    //注册页面
    @RequestMapping("/readdoc")
    public String readdoc(){
        return "readdoc";
    }

    //注册方法
    @RequestMapping("/addregister")
    public String register(HttpServletRequest request){

        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String password2 = request.getParameter("password2");
        if (password.equals(password2)){
            User userEntity = new User();

            userEntity.setUserName(username);
            userEntity.setUserPwd(password);
            userService.addUser(userEntity);
            return "login";
        }else {
            return "register";
        }
    }


    @PostMapping(value="/login")
    public String login(  User user,Map<String, Object> map ) {

        if(userService.loadUserByUserName(user.getUserName())!=null){
          List<User>  lus=userService.loadUserByUserName(user.getUserName());
            if(lus.get(0).getUserPwd().equals(user.getUserPwd())){
                map.put("user",lus.get(0));
                return "main";
            }
        }


        return "login";

    }

    @GetMapping("/mainController")
    public String main(){

        return "main";
    }

    @GetMapping("/logout")
    public String logout(){

        return "redirect:/security/toLogin";

    }

}